package com.sgb.kjwl.view.ui.activity.transport;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;

import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityStartTransportConfirmBinding;
import com.sgb.kjwl.di.transport.DaggerTransportComponent;
import com.sgb.kjwl.di.transport.TransportModule;
import com.sgb.kjwl.utils.ActivityJump;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.sgb.kjwl.view.ui.activity.transport.driver.trans.TransportFreightCollectionActivity;
import com.sgb.kjwl.view.ui.adapter.self.publish.ImageAdapter;
import com.sgb.kjwl.viewmodel.transport.SureStartTransportModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.DialogHelper;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * 确认发车
 */
public class SureStartTransportActivity extends AppActivity {
    public static final int START_TRANSPORT = 0;
    public static final int START_TRANSPORT_UN_INFOPRICE = 1;
    public static final int ARRIVED = 2;


    @Inject
    SureStartTransportModel viewModel;
    private ActivityStartTransportConfirmBinding binding;

    //图片上传
    private List<LocalMedia> selectList = new ArrayList<>();
    private ImageAdapter adapter;
    private List<String> urls = new ArrayList<>();
    private List<File> fileList = new ArrayList<>();
    private int currentImgIndex;
    private String urlStrings = "";
    private int pageState = 0;
    private String orderNo = "";
    private String infoPrice = "";


    public static void start(Context context, String orderNo, int pageState) {
        Intent intent = new Intent();
        intent.setClass(context, SureStartTransportActivity.class);
        intent.putExtra("pageState", pageState);
        intent.putExtra("orderNo", orderNo);
        context.startActivity(intent);
    }

    public static void start(Context context, String orderNo, int pageState, String infoPrice) {
        Intent intent = new Intent();
        intent.setClass(context, SureStartTransportActivity.class);
        intent.putExtra("pageState", pageState);
        intent.putExtra("orderNo", orderNo);
        intent.putExtra("infoPrice", infoPrice);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerTransportComponent.builder()
                .appComponent(appComponent)
                .transportModule(new TransportModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置沉浸式状态栏的上移问题
        setTileImmerse(true);
    }


    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(SureStartTransportActivity.this, R.layout.activity_start_transport_confirm);
        pageState = getIntent().getIntExtra("pageState", START_TRANSPORT);
        orderNo = getIntent().getStringExtra("orderNo");
        infoPrice = getIntent().getStringExtra("infoPrice");
        binding.topLayout.ivBack.setOnClickListener(this);
        adapter = new ImageAdapter(this, null, null, 3);
        binding.recyclerView.setLayoutManager(new GridLayoutManager(SureStartTransportActivity.this, 4));
        binding.recyclerView.setAdapter(adapter);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        binding.sureStart.setOnClickListener(this);
        initTips();

        viewModel.isSaved.observe(this,
                aBoolean -> sureStartTransportAndArrived());
    }

    private void initTips() {
        switch (pageState) {
            case START_TRANSPORT:
                binding.topLayout.titleView.setText("发车确认");
                binding.topTips.setText("请确保装到货物后再进行发车操作，避免与货主产生纠纷");
                binding.sureStart.setText("确认发车");
                break;
            case START_TRANSPORT_UN_INFOPRICE:
                binding.topLayout.titleView.setText("发车确认");
                binding.topTips.setText("确认发车后，" + infoPrice + "元信息费将转入货主账户，请确保装到货物后再操作");
                binding.sureStart.setText("确认发车");
                break;
            case ARRIVED:
                binding.topLayout.titleView.setText("送达确认");
                binding.topTips.setText("确认送达后，请及时收取本单运费费用");
                binding.sureStart.setText("确认到货");
                break;
        }

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;

            case R.id.sure_start:
                sureStartTransport();
                break;
        }
    }

    public void sureStartTransport() {
        DialogHelper.showProgressDialog(this, "文件上传中...").setCancelable(false);
        boolean unSelectedFile = fileList.size() == 0 || adapter.getFileList() == null
                || adapter.getFileList().size() == 0;
        if (unSelectedFile) {
//            sureStartTransportAndArrived();
            viewModel.saveLocation(orderNo);
            return;
        }
        urlStrings = "";
        currentImgIndex = 0;
        viewModel.uploadMutiFileModel(this, adapter.getFileList().get(currentImgIndex++));
    }


    public void uploadImgSuccess(String url) {
        dealUrlString(url);
        uploadImgAndSureStartTransport();
    }

    private void dealUrlString(String url) {
        if (TextUtils.isEmpty(urlStrings)) {
            urlStrings = url;
        } else {
            urlStrings = urlStrings + "," + url;
        }
    }

    private void uploadImgAndSureStartTransport() {
        if (currentImgIndex < fileList.size()) {
            viewModel.uploadMutiFileModel(this, adapter.getFileList().get(currentImgIndex++));
        } else {
            //图片上传完成后的操作
//            sureStartTransportAndArrived();
            viewModel.saveLocation(orderNo);
        }
    }

    // 确认发车和确认送达前需要上传一下位置信息
    private void sureStartTransportAndArrived() {
        if (pageState == START_TRANSPORT || pageState == START_TRANSPORT_UN_INFOPRICE) {
            viewModel.sureStartTransport(this, orderNo, urlStrings);
        } else if (pageState == ARRIVED) {
            viewModel.sureArrived(this, orderNo, urlStrings);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {// 图片结果回调
                // 图片、视频、音频选择结果回调
                selectList = PictureSelector.obtainMultipleResult(data);
                fileList.clear();
                urls.clear();
                for (LocalMedia localMedia : selectList) {
                    File file = new File(localMedia.getRealPath());
                    fileList.add(file);
                    urls.add(localMedia.getRealPath());
                }
                adapter.setDatas(selectList, urls);
                adapter.setFileList(fileList);
            }
        }
        if (requestCode == 255) {
            if (data == null) {
                return;
            }
        }
    }


    public void postSureSuccessEvent() {
        EventBus.getDefault().post(LogisticsEvent.make().setMessageTag(EventConstant.EVENT_SURE_START_TRANSPORT_SUCCESS));
        if (pageState == ARRIVED) {
            ActivityJump.jumpToActivity(this, TransportFreightCollectionActivity.class, Pair.create("infoPrice", infoPrice),Pair.create("orderNo",orderNo));
        }
        finish();
    }


}

